package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 定时处理支付超时订单
     */
    @Scheduled(cron = "0 0/3 * * * ?")//每三分钟检查是否由支付超时订单
    public void processTimeOutOrder(){
        log.info("定时处理支付超时订单中");

        LocalDateTime time = LocalDateTime.now().minusMinutes(15);//如果订单已经下单超过15分钟未支付,则需要进行处理
        List<Orders> ordersList = orderMapper.process(Orders.PENDING_PAYMENT, time);
        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);//设置订单已取消
                orders.setCancelTime(LocalDateTime.now());//设置订单取消时间
                orders.setCancelReason("订单支付超时,已自定取消");//设置订单取消原因
                //修改订单
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 定时处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天晚上1点整自动完成派送中的订单
    public void processDeliveryOrder(){
        log.info("自动处理派送中订单");

        LocalDateTime time = LocalDateTime.now().minusMinutes(60);//处理前一天之前的订单
        List<Orders> ordersList = orderMapper.process(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }



















}
